/**
 * 机构树，主要用于显示树结构的机构人员数据，带排序、右键菜单功能
 * json格式：[{"id":"OmOrg#10","leaf":false,...},{...},...]
 * java类：com.augurit.common.system.common.OrgTreeNode
 */
Ext.namespace("Ext.ux");

Ext.ux.OrgTree = Ext.extend(Ext.tree.TreePanel, {

	// 获取数据的URL
	url: '',
	
	// 是否使用箭头图标
	useArrows: true,
	
	// 是否显示动画
	animate: true,
	
	// 是否允许拖放
	enableDD: true,
	
	// 是否显示边框
	border: false,
	
	// 是否显示根节点
	rootVisible: true,
	
	// 是否自动显示滚动条
	autoScroll: true,
	containerScroll: true,
	
	// 设置间隔样式
	bodyStyle: 'padding:3px',

	//是否显示右键菜单
	isDisplayMenu:'',
	
	
	// 组件初始化
	initComponent: function(){

		// 根节点
    	this.root = new Ext.tree.AsyncTreeNode({
			text: '机构用户树',
			draggable: false,	// 不允许拖放
			leaf: false,		// 非叶子节点
			iconCls: 'icon-tree-root',
			orgId: "-1",		// 根节点的默认ID为“-1”
			partyType: 'ORG',	//默认为机构类型
			canManager: false	//默认为不能管理机构
		});
		
		// 数据加载器
		this.loader = new Ext.tree.TreeLoader({
			dataUrl: this.url,
			listeners: {
				"beforeload": function(treeLoader, node){
					//节点类型（机构 或 岗位）
					treeLoader.baseParams.partyType = node.attributes.partyType;

					//节点ID
					if(node.attributes.orgId != null){
						treeLoader.baseParams.orgId = node.attributes.orgId;
					}
					if(node.attributes.posId != null){
						treeLoader.baseParams.posId = node.attributes.posId;
					}
				}
			}
		});
		
		// 调用父类初始化
		Ext.ux.OrgTree.superclass.initComponent.call(this);

		
		//增加根节点的右键菜单
		var rootMenu = new Ext.menu.Menu({
			items: [{
				text: '新增顶级机构',
				iconCls: 'add-child-org',
				handler:this.addTopOrg,
				scope: this
			},'-',{
				text: '刷新',
				iconCls: 'refresh',
				handler: this.refreshOrg,
				scope: this
			}]
		});
		
		// 定义机构节点的右键菜单
		var orgMenu = new Ext.menu.Menu({
			items: [{
				text: '新增下级机构',
				iconCls: 'add-child-org',
				handler: this.addChildOrg,
				scope: this
			},'-',{
				text: '新增下级岗位',
				iconCls: 'add-position',
				handler:this.orgAddPosition,
				scope: this
			},'-',{
				text: '新增机构用户',
				iconCls: 'add-user',
				handler:this.orgAddUser,
				scope: this
			},'-',{
				text: '新增已有机构用户',
				iconCls: 'add-user',
				handler:this.orgSelectUser,
				scope: this
			},'-',{
				text: '删除本级机构',
				iconCls: 'delete-org',
				handler:this.deleteOrg,
				scope: this
			},'-',{
				text: '刷新',
				iconCls: 'refresh',
				handler: this.refreshOrg,
				scope: this
			}]
		});
		
		
		// 定义岗位节点的右键菜单
		var positionMenu = new Ext.menu.Menu({
			items: [{
				text: '新增下级岗位',
				iconCls: 'add-child-position',
				handler: this.addChildPosition,
				scope:this	
			},'-',{
				text: '新增岗位用户',
				iconCls: 'add-user',
				handler:this.posAddUser,
				scope: this
			},'-',{
				text: '删除本级岗位',
				iconCls: 'delete-position',
			    handler:this.deletePosition,
			    scope: this
			},'-',{
				text: '刷新',
				iconCls: 'refresh',
				handler: this.refreshOrg,
				scope: this
			}]
		});
	
		// 定义岗位用户节点的右键菜单
		var posUserMenu = new Ext.menu.Menu({
			items: [{
				text: '删除岗位用户',
				iconCls: 'delete-user',
				handler:this.deleteUserFromPos,
				scope: this
			}]
		});
		
		// 定义机构用户节点的右键菜单
		var orgUserMenu = new Ext.menu.Menu({
			items: [{
				text: '删除机构用户',
				iconCls: 'delete-user',
				handler:this.deleteUserFromOrg,
				scope: this
			}]
		});
		
		//根据isDisplayMenu配置项判断需要注册右键菜单
		if(this.isDisplayMenu){
			this.on('contextmenu', function(node, e){			
				if(node.attributes.canManager){
					e.preventDefault();
					node.select();
					
					//注册节点右键菜单
					if(node.attributes.partyType.indexOf('ORG') == 0 && node.attributes.orgId == -1){
						rootMenu.showAt(e.getXY());
					}
					else if(node.attributes.partyType.indexOf('ORG') == 0){
						orgMenu.showAt(e.getXY());
					}
					else if(node.attributes.partyType.indexOf('POS') == 0){
						positionMenu.showAt(e.getXY());
					}
					else if(node.attributes.partyType.indexOf('USER') == 0){
						if(node.parentNode.attributes.partyType.indexOf('ORG') == 0){
							orgUserMenu.showAt(e.getXY());
						}
						else{
							posUserMenu.showAt(e.getXY());
						}
						
					}
				}else{
					Ext.Msg.alert('系统提示','您没有访问该节点的权限!');
				}
			}, this);
		}

		//拖放节点，包括拖动机构到另一机构、拖动用户到机构等等
		this.on('beforenodedrop', function(e){
			var dragDropWin = new Ext.ux.org.omorg.OrgNodeDragDropWindow({dropNode:e.dropNode, targetNode:e.target});
			dragDropWin.show();
			return false;
		});
		
		
		this.initRootCanManage();
		
		// 展开根节点
		this.getRootNode().expand();
	},
	
	// 组件事件初始化
	initEvents: function(){
        Ext.tree.TreePanel.superclass.initEvents.call(this);

        if(this.containerScroll){
            Ext.dd.ScrollManager.register(this.body);
        }
        if((this.enableDD || this.enableDrop) && !this.dropZone){
           
             this.dropZone = new Ext.ux.OrgTreeDropZone(this, this.dropConfig || {
               ddGroup: this.ddGroup || "TreeDD", appendOnly: this.ddAppendOnly === true
           });
        }
        if((this.enableDD || this.enableDrag) && !this.dragZone){
           
            this.dragZone = new Ext.tree.TreeDragZone(this, this.dragConfig || {
               ddGroup: this.ddGroup || "TreeDD",
               scroll: this.ddScroll
           });
        }
        this.getSelectionModel().init(this);
    },

	//如果是系统管理员，则根节点可管理
	initRootCanManage: function(){
		Ext.Ajax.request({
			url: 'om-user!isSystemAdmin.action',
			success: function(response){
				if(Ext.decode(response.responseText).canManager)
					this.root.attributes.canManager = true;
			},
			scope: this
		});
	},

    //弹出新增顶级机构窗口
	addTopOrg: function(){
		var inputWin = new Ext.ux.org.omorg.OrgDetailWindow({id:'orgDetailWindow', title:'新增顶级机构'});
		inputWin.show();
	},

	//弹出新增下级机构窗口
	addChildOrg: function(){
		var node = this.getSelectionModel().getSelectedNode();
		
		//父机构ID和名称
		var parentOrgId = node.attributes.orgId;
		var parentOrgName = node.text;
		
		var inputWin = new Ext.ux.org.omorg.OrgDetailWindow({id:'orgDetailWindow', title:'新增下级机构', parentOrgId:parentOrgId, parentOrgName:parentOrgName});
		inputWin.show();
	},

	//节点刷新
	refreshOrg: function(){
		var node = this.getSelectionModel().getSelectedNode();
		if(node != null && node.attributes.partyType != 'USER'){
			node.reload();
		}else{
			this.root.reload();
		}
	},

	//刷新父节点
	refreshParentNode: function(){
		var node = this.getSelectionModel().getSelectedNode();
		var parNode = node.parentNode;
		if(parNode != null && parNode.attributes.partyType != 'USER'){
			parNode.reload();
		}else{
			this.root.reload();
		}
	},

	//机构下新增岗位
	orgAddPosition: function (){
		var node = this.getSelectionModel().getSelectedNode();
		var orgId = node.attributes.orgId;
		var orgName = node.text;
		this.openPosInputWin(orgId, orgName, null, null);
	},

	//新增下级岗位
	openPosInputWin: function(orgId, orgName, parentPosId, parentPosName) {
		var win = new Ext.ux.org.omorg.PosDetailWindow({
			title: '新增下级岗位',
			orgId: orgId,
			orgName: orgName,
			parentPosId: parentPosId,
			parentPosName: parentPosName
		});
		win.show();
	},

	//机构下新增用户
	orgAddUser: function(){
		var node = this.getSelectionModel().getSelectedNode();
		var orgId = node.attributes.orgId;
		
		this.openUserInputWin(orgId, null, '新增机构用户');
	},

	//添加已有用户到机构
	orgSelectUser: function (){
		var node = this.getSelectionModel().getSelectedNode();
		var orgId = node.attributes.orgId;
		this.openUserSelectWin(orgId, '新增已有机构用户');
	},

	//新增用户
	openUserInputWin: function(orgId, posId, winTitle) {
		var win = new Ext.ux.org.omorg.UserDetailWindow({
			title: winTitle,
			orgId: orgId,
			posId: posId
		});
		win.show();
	},

	//打开选择已有用户窗口
	openUserSelectWin: function(orgId, winTitle) {
		var win = new Ext.ux.org.omorg.UserAddToOrgWindow({
			title: winTitle, 
			orgId: orgId
		});
		win.show();
	},
	
	//删除机构
	deleteOrg: function(){
		var node = this.getSelectionModel().getSelectedNode();
		var orgId = node.attributes.orgId;
	
		Ext.MessageBox.show({
		    title: '系统提示',
		    msg: '确认要删除选中的机构吗？<br/><font color="red">注意</font>：删除机构将删除该机构下的所有子机构。',
		    buttons: Ext.Msg.YESNO,
		    icon: Ext.MessageBox.QUESTION,
		    width: 350,
		    fn: function(btn){
		    	if(btn == 'yes'){
			    	Ext.Ajax.request({
						url:'om-org!delete.action',
						success:function(){
							Ext.getCmp('orgTree').refreshParentNode();
						},
						failure: function(form, action) {
							Ext.Msg.alert('系统提示', '删除机构失败！');
						},
						method: 'POST',
						params:{
							orgIds: orgId
						},
						waitMsg : '正在删除数据，稍候...'
					});
				}
			}
		});
	},

	//新增子岗位
	addChildPosition: function(){
		var node = this.getSelectionModel().getSelectedNode();
		var parentPosId = node.attributes.posId;
		var parentPosName = node.text;
		var orgId = node.attributes.orgId;
		var orgName = node.attributes.parentGroupName;
		this.openPosInputWin(orgId, '父岗位机构', parentPosId, parentPosName);
	},

	//新增岗位用户
	posAddUser: function(){
		var node = this.getSelectionModel().getSelectedNode();
		var posId = node.attributes.posId;
		this.openUserInputWin(null, posId, '新增岗位用户');
	},

	//删除岗位
	deletePosition: function(){
		var node = this.getSelectionModel().getSelectedNode();
		var posId = node.attributes.posId;

		Ext.MessageBox.show({
		    title: '系统提示',
		    msg: '确认要删除选中的岗位吗？<br/><font color="red">注意</font>：删除岗位将删除该岗位下的所有子岗位。',
		    buttons: Ext.Msg.YESNO,
		    icon: Ext.MessageBox.QUESTION,
		    fn: function(btn){
		    	if(btn == 'yes'){
					Ext.Ajax.request({
						url:'om-position!delete.action',
						success:function(){
							Ext.getCmp('orgTree').refreshParentNode();
						},
						failure: function(form, action) {
							Ext.Msg.alert('系统提示', '删除岗位失败！');
						},
						method: 'POST',
						params:{
							posIds: posId
						},
						waitMsg : '正在删除数据，稍候...'
					});
				}
			},
			width: 350
		});  
	},

	//删除机构用户
	deleteUserFromOrg: function(){
		var node = this.getSelectionModel().getSelectedNode();
		var userId = node.attributes.userId;
		var orgId = node.parentNode.attributes.orgId;
		
		Ext.MessageBox.show({
		    title: '系统提示',
		    msg: '确认要删除选中的用户吗？',
		    buttons: Ext.Msg.YESNO,
		    icon: Ext.MessageBox.QUESTION,
		    fn: function(btn){
		    	if(btn == 'yes'){
					Ext.Ajax.request({
						url:'om-user!deleteFromOrg.action',
						success:function(){
							this.refreshParentNode();
						},
						failure: function(form, action) {
							Ext.Msg.alert('系统提示', '删除用户失败！');
						},
						params:{
							userIds: userId,
							orgId: orgId
						},
						waitMsg: '正在删除数据，稍候...',
						scope: this
					});
				}
			},
			width: 350,
		    scope: this
		});
	},
	//删除岗位用户
	deleteUserFromPos: function(){
		var node = this.getSelectionModel().getSelectedNode();
		var userId = node.attributes.userId;
		var posId = node.parentNode.attributes.posId;
		
		Ext.MessageBox.show({
		    title: '系统提示',
		    msg: '确认要删除选中的用户吗？',
		    buttons: Ext.Msg.YESNO,
		    icon: Ext.MessageBox.QUESTION,
		    fn: function(btn){
		    	if(btn == 'yes'){
					Ext.Ajax.request({
						url:'om-user!deleteFromPos.action',
						success:function(){
							this.refreshParentNode();
						},
						failure: function(form, action) {
							Ext.Msg.alert('系统提示', '删除用户失败！');
						},
						params:{
							userIds: userId,
							posId: posId
						},
						waitMsg: '正在删除数据，稍候...',
						scope: this
					});
				}
			},
			width: 350,
		    scope: this
		});
	}
});